'use client';
import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Input,
  Select,
  Tag,
  Modal,
  Form,
  Popconfirm,
  message,
  Typography,
  Divider,
  Row,
  Col,
  Space,
  Checkbox,
  Badge,
  Statistic,
  DatePicker
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { SearchOutlined, EditOutlined, DeleteOutlined, CheckCircleOutlined, CloseCircleOutlined, FilterOutlined, PlusOutlined } from '@ant-design/icons';
import { commentService, type Comment as ServiceComment } from '@/service/comment.service';
import { sensitiveWordService, type SensitiveWord as ServiceSensitiveWord } from '@/service/sensitive-word.service';

const { Title, Text, Paragraph } = Typography;
const { Search, TextArea } = Input;
const { Option } = Select;

// 使用后端的敏感词数据类型
interface SensitiveWord extends ServiceSensitiveWord {}

// 评论状态定义
const COMMENT_STATUS = {
  ACTIVE: 'active',
  DELETED: 'deleted'
};

// 评论状态映射
const statusMap: Record<string, { label: string; color: string }> = {
  [COMMENT_STATUS.ACTIVE]: { label: '正常', color: 'green' },
  [COMMENT_STATUS.DELETED]: { label: '已删除', color: 'red' }
};

interface Comment extends ServiceComment {
  authorName?: string;
  articleTitle?: string;
  likes?: number;
  likeCount?: number;
  isSensitive?: boolean;
  status?: string;
  replyToName?: string;
  authorId?: number;
}

// 使用后端的敏感词数据类型
interface SensitiveWord extends ServiceSensitiveWord {}

const CommentManagement: React.FC = () => {
  // 状态定义
  const [comments, setComments] = useState<Comment[]>([]);
  const [filteredComments, setFilteredComments] = useState<Comment[]>([]);
  const [selectedComments, setSelectedComments] = useState<number[]>([]);
  const [loading, setLoading] = useState(false);
  const [currentComment, setCurrentComment] = useState<Comment | null>(null);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isReplyModalVisible, setIsReplyModalVisible] = useState(false);
  const [isSensitiveWordModalVisible, setIsSensitiveWordModalVisible] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [selectedStatus, setSelectedStatus] = useState<string>('all');
  // const [selectedArticle, setSelectedArticle] = useState<string>('all');
  // const [selectedAuthor, setSelectedAuthor] = useState<string>('all');
  const [commentForm] = Form.useForm();
  const [replyForm] = Form.useForm();
  const [sensitiveWordForm] = Form.useForm();
  const [sensitiveWords, setSensitiveWords] = useState<SensitiveWord[]>([]);
  
  // 分页状态
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  
  // 获取文章列表（用于筛选）
  // const [articles, setArticles] = useState<Array<{ id: number; title: string }>>([]);
  
  // 获取作者列表（用于筛选）
  // const [authors, setAuthors] = useState<Array<{ id: number; name: string }>>([]);

  // 获取评论列表
  const fetchComments = async (page: number = pagination.current, pageSize: number = pagination.pageSize) => {
    setLoading(true);
    try {
      // 构建查询参数
      const params: any = {
        page,
        pageSize
      };

      // 添加筛选条件
      if (selectedStatus !== 'all') {
        params.status = selectedStatus === COMMENT_STATUS.ACTIVE ? 1 : 0;
      }
      
      // if (selectedArticle !== 'all') {
      //   params.articleId = parseInt(selectedArticle);
      // }
      
      // if (selectedAuthor !== 'all') {
      //   params.userId = parseInt(selectedAuthor);
      // }
      
      if (searchText) {
        params.keyword = searchText;
      }

      const response = await commentService.getCommentList(params);
      
      // 转换为前端需要的格式
      const commentsData = response.items.map(comment => ({
        ...comment,
        userId: comment.author?.id || comment.userId,
        authorName: comment.author?.username || comment.username || '匿名用户',
        articleTitle: comment.artinfo?.title || comment.articleTitle,
        avatar: comment.author?.avatar || comment.avatar,
        // likes: comment.likeCount || 0,
        isActive: comment.isActive !== undefined ? comment.isActive : 1,
        status: comment.isActive === 1 ? COMMENT_STATUS.ACTIVE : COMMENT_STATUS.DELETED,
        isSensitive: false
      }));
      
      setComments(commentsData);
      setFilteredComments(commentsData);
      setPagination({
        current: response.page,
        pageSize: response.pageSize,
        total: response.total
      });
    } catch (error) {
      console.error('获取评论列表失败:', error);
      message.error('获取评论列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchComments();
    fetchSensitiveWords(); // 加载敏感词列表
  }, []);

  // 获取敏感词列表
  const fetchSensitiveWords = async () => {
    try {
      const words = await sensitiveWordService.getAllSensitiveWords();
      setSensitiveWords(words);
    } catch (error) {
      console.error('获取敏感词列表失败:', error);
    }
  };

  // 筛选评论 - 当筛选条件变化时重新加载
  useEffect(() => {
    fetchComments(1); // 重置到第1页
  }, [searchText, selectedStatus]);

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchText(value);
  };

  // 处理编辑评论
  const handleEditComment = (comment: Comment) => {
    setCurrentComment(comment);
    commentForm.setFieldsValue({
      content: comment.content
    });
    setIsModalVisible(true);
  };

  // 处理保存评论
  const handleSaveComment = async () => {
    try {
      const values = await commentForm.validateFields();
      if (currentComment) {
        // 更新评论
        await commentService.updateCommentContent(currentComment.id, values.content);
        message.success('评论更新成功');
        setIsModalVisible(false);
        commentForm.resetFields();
        setCurrentComment(null);
        fetchComments();
      }
    } catch (error: any) {
      console.error('保存评论失败:', error);
      message.error(error?.message || '保存评论失败');
    }
  };

  // 处理删除/恢复评论
  const handleToggleCommentStatus = async (id: number, currentStatus: number) => {
    try {
      // 切换状态：0->1(恢复), 1->0(删除)
      const newStatus = currentStatus === 1 ? 0 : 1;
      await commentService.updateCommentStatus(id, newStatus);
      message.success(newStatus === 1 ? '评论已恢复' : '评论已删除');
      fetchComments();
    } catch (error: any) {
      console.error('操作评论失败:', error);
      message.error(error?.message || '操作评论失败');
    }
  };

  // 处理批量操作
  const handleBatchAction = async (action: string) => {
    if (selectedComments.length === 0) {
      message.warning('请先选择要操作的评论');
      return;
    }
    
    Modal.confirm({
      title: `确认${action === 'delete' ? '删除' : '操作'}`,
      content: `确定要${action === 'delete' ? '删除' : '操作'}选中的 ${selectedComments.length} 条评论吗？`,
      onOk: async () => {
        try {
          if (action === 'delete') {
            // 批量删除（软删除：将isActive设置为0）
            for (const id of selectedComments) {
              await commentService.updateCommentStatus(id, 0);
            }
          }
          
          message.success(`成功${action === 'delete' ? '删除' : '操作'} ${selectedComments.length} 条评论`);
          setSelectedComments([]);
          fetchComments();
        } catch (error: any) {
          console.error('批量操作失败:', error);
          message.error(error?.message || '批量操作失败');
        }
      }
    });
  };

  // 处理选择评论
  const handleSelectChange = (selectedRowKeys: React.Key[]) => {
    setSelectedComments(selectedRowKeys.map(key => Number(key)));
  };

  // 处理回复评论
  // const handleReplyComment = (comment: Comment) => {
  //   setCurrentComment(comment);
  //   replyForm.setFieldsValue({ replyContent: '' });
  //   setIsReplyModalVisible(true);
  // };

  // 处理保存回复
  const handleSaveReply = () => {
    replyForm.validateFields().then(values => {
      if (currentComment) {
        // 创建新回复评论
        const newReply: Comment = {
          id: comments.length + 1,
          content: values.replyContent,
          articleId: currentComment.articleId,
          userId: 1, // 假设当前用户是管理员
          articleTitle: currentComment.articleTitle || '',
          authorId: 1, // 假设当前用户是管理员
          authorName: '管理员',
          status: COMMENT_STATUS.ACTIVE,
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
          replyTo: currentComment.id,
          replyToName: currentComment.authorName || '',
          likes: 0,
          isSensitive: false
        };
        
        setComments([...comments, newReply]);
        message.success('回复成功');
      }
      setIsReplyModalVisible(false);
      replyForm.resetFields();
      setCurrentComment(null);
    }).catch(info => {
      console.log('表单验证失败:', info);
    });
  };

  // 添加敏感词
  const handleAddSensitiveWord = async () => {
    try {
      const values = await sensitiveWordForm.validateFields();
      
      // 调用后端接口添加敏感词
      await sensitiveWordService.createSensitiveWord(values.word);
      
      // 重新加载敏感词列表
      await fetchSensitiveWords();
      
      message.success('敏感词添加成功');
      setIsSensitiveWordModalVisible(false);
      sensitiveWordForm.resetFields();
    } catch (error: any) {
      if (error.errorFields) {
        // 表单验证错误
        console.log('表单验证失败:', error);
      } else {
        // API 调用错误
        console.error('添加敏感词失败:', error);
        message.error(error?.message || '添加敏感词失败');
      }
    }
  };

  // 删除敏感词
  const handleDeleteSensitiveWord = async (id: number) => {
    try {
      await sensitiveWordService.deleteSensitiveWord(id);
      
      // 重新加载敏感词列表
      await fetchSensitiveWords();
      
      message.success('敏感词删除成功');
    } catch (error: any) {
      console.error('删除敏感词失败:', error);
      message.error(error?.message || '删除敏感词失败');
    }
  };

  // 计算统计数据
  const totalComments = comments.length;
  const activeComments = comments.filter(comment => comment.status === COMMENT_STATUS.ACTIVE).length;
  const deletedComments = comments.filter(comment => comment.status === COMMENT_STATUS.DELETED).length;
  // const sensitiveComments = comments.filter(comment => comment.isSensitive).length;

  // 评论列表列配置
  const columns: ColumnsType<Comment> = [
    {
      title: (
        <Checkbox
          checked={selectedComments.length === filteredComments.length && filteredComments.length > 0}
          indeterminate={selectedComments.length > 0 && selectedComments.length < filteredComments.length}
          onChange={(e) => {
            if (e.target.checked) {
              setSelectedComments(filteredComments.map(comment => comment.id));
            } else {
              setSelectedComments([]);
            }
          }}
        />
      ),
      key: 'selection',
      width: 40,
      render: (_, record) => (
        <Checkbox
          checked={selectedComments.includes(record.id)}
          onChange={(e) => {
            if (e.target.checked) {
              setSelectedComments([...selectedComments, record.id]);
            } else {
              setSelectedComments(selectedComments.filter(id => id !== record.id));
            }
          }}
        />
      )
    },
    {
      title: '评论内容',
      dataIndex: 'content',
      key: 'content',
      width: 200,
      ellipsis: {
        showTitle: false,
      },
      render: (content: string, record: Comment) => (
        <div>
          <Paragraph ellipsis={{ rows: 2, tooltip: content }} style={{ marginBottom: 0 }}>
            {content}
          </Paragraph>
          {record.isSensitive && <Tag color="red">包含敏感词</Tag>}
          {record.replyTo && (
            <Text type="secondary" style={{ fontSize: '12px' }}>
              回复 <Text style={{ color: '#1890ff' }}>@{record.replyToName}</Text>
            </Text>
          )}
        </div>
      )
    },
    {
      title: '文章',
      dataIndex: 'articleTitle',
      key: 'articleTitle',
      width: 200,
      ellipsis: true
    },
    {
      title: '评论者',
      dataIndex: 'authorName',
      key: 'authorName',
      width: 100
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => (
        <Tag color={statusMap[status]?.color}>
          {statusMap[status]?.label}
        </Tag>
      )
    },
    // {
    //   title: '点赞数',
    //   dataIndex: 'likes',
    //   key: 'likes',
    //   width: 80,
    //   align: 'right'
    // },
    {
      title: '评论时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 150,
      render: (time: string) => new Date(time).toLocaleString()
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record: Comment) => (
        <Space size="middle">
          {/*record.status === COMMENT_STATUS.PENDING && (
            <>
              {/*<Button size="small" type="primary" icon={<CheckCircleOutlined />} onClick={() => handleApprove(record.id)}>
                通过
              </Button>
              <Button size="small" danger icon={<CloseCircleOutlined />} onClick={() => handleReject(record.id)}>
                拒绝
              </Button>*//*}
            </>
          )*/}
          <Button size="small" icon={<EditOutlined />} onClick={() => handleEditComment(record)}>
            编辑
          </Button>
          {/* <Button size="small" onClick={() => handleReplyComment(record)}>
            回复
          </Button> */}
          <Popconfirm
            title={`确定要${record.isActive === 1 ? '删除' : '恢复'}此评论吗?`}
            onConfirm={() => handleToggleCommentStatus(record.id, record.isActive)}
            okText="确定"
            cancelText="取消"
          >
            <Button size="small" danger={record.isActive === 1} type={record.isActive === 0 ? 'primary' : 'default'} icon={<DeleteOutlined />}>
              {record.isActive === 1 ? '删除' : '恢复'}
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div style={{ padding: '20px' }}>
      <Title level={3}>评论管理</Title>
      
      {/* 批量操作栏 */}
      <Card style={{ marginBottom: '16px' }}>
        <Space>
          <Text>已选择 {selectedComments.length} 条评论</Text>
          <Button danger onClick={() => handleBatchAction('delete')} disabled={selectedComments.length === 0}>
            批量删除
          </Button>
        </Space>
      </Card>
      
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        {/* 评论统计卡片 */}
        <Col span={6}>
          <Card title="评论统计概览" bordered={true}>
            <div style={{ marginBottom: '16px' }}>
              <StatisticComponent title="总评论数" value={totalComments} suffix="条" />
            </div>
            <div style={{ marginBottom: '16px' }}>
              <StatisticComponent title="正常" value={activeComments} suffix="条" valueStyle={{ color: '#52c41a' }} />
            </div>
            <div style={{ marginBottom: '16px' }}>
              <StatisticComponent title="已删除" value={deletedComments} suffix="条" valueStyle={{ color: '#ff4d4f' }} />
            </div>
            {/* <div style={{ marginBottom: '16px' }}>
              <StatisticComponent title="敏感评论" value={sensitiveComments} suffix="条" valueStyle={{ color: '#fa541c' }} />
            </div> */}
            
            <Divider style={{ margin: '16px 0' }} />
            
            <Button 
              type="primary" 
              icon={<PlusOutlined />} 
              onClick={() => setIsSensitiveWordModalVisible(true)}
              style={{ width: '100%' }}
            >
              管理敏感词
            </Button>
          </Card>
        </Col>
        
        {/* 评论列表 */}
        <Col span={18}>
          {/* 筛选工具栏 */}
          <Card style={{ marginBottom: '16px' }}>
            <Row gutter={[16, 16]}>
              <Col span={12}>
                <Search
                  placeholder="搜索评论内容/作者/文章"
                  allowClear
                  onSearch={handleSearch}
                  enterButton
                />
              </Col>
              <Col span={12}>
                <Select
                  placeholder="状态筛选"
                  value={selectedStatus}
                  onChange={setSelectedStatus}
                  style={{ width: '100%' }}
                  allowClear
                >
                  <Option value="all">全部状态</Option>
                  <Option value={COMMENT_STATUS.ACTIVE}>正常</Option>
                  <Option value={COMMENT_STATUS.DELETED}>已删除</Option>
                </Select>
              </Col>
            </Row>
          </Card>
          
          <Card title="评论列表">
            <Table
              columns={columns}
              dataSource={filteredComments}
              rowKey="id"
              loading={loading}
              pagination={{
                current: pagination.current,
                pageSize: pagination.pageSize,
                total: pagination.total,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`,
                onChange: (page, pageSize) => {
                  fetchComments(page, pageSize);
                },
                onShowSizeChange: (current, size) => {
                  fetchComments(1, size);
                }
              }}
              scroll={{ x: 1400 }}
            />
          </Card>
        </Col>
      </Row>

      {/* 评论编辑模态框 */}
      <Modal
        title="编辑评论"
        open={isModalVisible}
        onOk={handleSaveComment}
        onCancel={() => {
          setIsModalVisible(false);
          commentForm.resetFields();
          setCurrentComment(null);
        }}
        okText="保存"
        cancelText="取消"
        width={600}
      >
        <Form form={commentForm} layout="vertical">
          <Form.Item
            label="评论内容"
            name="content"
            rules={[{ required: true, message: '请输入评论内容' }]}
          >
            <TextArea rows={4} placeholder="请输入评论内容" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 回复评论模态框 */}
      <Modal
        title={`回复评论 - @${currentComment?.authorName}`}
        open={isReplyModalVisible}
        onOk={handleSaveReply}
        onCancel={() => {
          setIsReplyModalVisible(false);
          replyForm.resetFields();
          setCurrentComment(null);
        }}
        okText="回复"
        cancelText="取消"
        width={600}
      >
        <Form form={replyForm} layout="vertical">
          <Form.Item
            label={`回复 @${currentComment?.authorName}`}
            name="replyContent"
            rules={[{ required: true, message: '请输入回复内容' }]}
          >
            <TextArea rows={4} placeholder="请输入回复内容" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 敏感词管理模态框 */}
      <Modal
        title="敏感词管理"
        open={isSensitiveWordModalVisible}
        onCancel={() => {
          setIsSensitiveWordModalVisible(false);
          sensitiveWordForm.resetFields();
        }}
        footer={null}
        width={600}
      >
        <Form form={sensitiveWordForm} layout="vertical" onFinish={handleAddSensitiveWord}>
          <Form.Item
            label="添加敏感词"
            name="word"
            rules={[{ required: true, message: '请输入敏感词' }, { min: 1, max: 20, message: '敏感词长度应在 1-20 个字符之间' }]}
          >
            <Input placeholder="请输入敏感词" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              添加敏感词
            </Button>
          </Form.Item>
        </Form>
        
        <Divider />
        
        <Title level={5}>已添加的敏感词</Title>
        <Space wrap>
          {sensitiveWords.map(word => (
            <Tag
              key={word.id}
              closable
              onClose={() => handleDeleteSensitiveWord(word.id)}
              style={{ margin: '4px' }}
            >
              {word.word} <span style={{ color: '#999' }}>({word.usageCount}次)</span>
            </Tag>
          ))}
        </Space>
      </Modal>
    </div>
  );
};

// 导入缺失的Statistic组件
import { Statistic as AntdStatistic } from 'antd';
const StatisticComponent = AntdStatistic;

export default CommentManagement;
